#!/bin/bash
# -*- tab-width:4;indent-tabs-mode:nil -*-
# ex: ts=4 sw=4 et

RUNNER_SCRIPT_DIR={{runner_script_dir}}
RUNNER_SCRIPT=${0##*/}

RUNNER_BASE_DIR={{runner_base_dir}}
SHIRASU_BASE_DIR=$RUNNER_BASE_DIR{{platform_lib_dir}}
RUNNER_ETC_DIR={{runner_etc_dir}}
RUNNER_LOG_DIR={{runner_log_dir}}
PIPE_DIR={{pipe_dir}}
RUNNER_USER={{runner_user}}
SSL_DIST_CONFIG={{platform_data_dir}}/ssl_distribution.args_file

# Make sure this script is running as the appropriate user
if [ "$RUNNER_USER" -a "x$LOGNAME" != "x$RUNNER_USER" ]; then
    type -p sudo > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "sudo doesn't appear to be installed and your EUID isn't $RUNNER_USER" 1>&2
        exit 1
    fi
    echo "Attempting to restart script through sudo -u $RUNNER_USER"
    exec sudo -u $RUNNER_USER -i $RUNNER_SCRIPT_DIR/$RUNNER_SCRIPT $@
fi

# Warn the user if ulimit -n is less than 1024
ULIMIT_F=`ulimit -n`
if [ "$ULIMIT_F" -lt 1024 ]; then
    echo "!!!!"
    echo "!!!! WARNING: ulimit -n is ${ULIMIT_F}; 1024 is the recommended minimum."
    echo "!!!!"
fi

# Make sure CWD is set to runner base dir
cd $RUNNER_BASE_DIR

# Make sure log directory exists
mkdir -p $RUNNER_LOG_DIR

# Extract the target node name from node.args
NAME_ARG=`grep '\-[s]*name' $RUNNER_ETC_DIR/vm.args`
if [ -z "$NAME_ARG" ]; then
    echo "vm.args needs to have either -name or -sname parameter."
    exit 1
fi

# Extract the target cookie
COOKIE_ARG=`grep '\-setcookie' $RUNNER_ETC_DIR/vm.args`
if [ -z "$COOKIE_ARG" ]; then
    echo "vm.args needs to have a -setcookie parameter."
    exit 1
fi

# Identify the script name
SCRIPT=`basename $0`

# Parse out release and erts info
START_ERL=`cat $SHIRASU_BASE_DIR/releases/start_erl.data`
ERTS_VSN=${START_ERL% *}
APP_VSN=${START_ERL#* }

# Add ERTS bin dir to our path
ERTS_PATH=$RUNNER_BASE_DIR/erts-$ERTS_VSN/bin

# Setup command to control the node
NODETOOL="/usr/bin/env escript $ERTS_PATH/nodetool $NAME_ARG $COOKIE_ARG"

# Scrape out SSL distribution config info from vm.args into $SSL_DIST_CONFIG
rm -f $SSL_DIST_CONFIG
sed -n '/Begin SSL distribution items/,/End SSL distribution items/p' \
    $RUNNER_ETC_DIR/vm.args > $SSL_DIST_CONFIG

# Check the first argument for instructions
case "$1" in
    start)
        # Make sure there is not already a node running
        RES=`$NODETOOL ping`
        if [ "$RES" = "pong" ]; then
            echo "Node is already running!"
            exit 1
        fi
        HEART_COMMAND="$RUNNER_SCRIPT_DIR/$SCRIPT start"
        export HEART_COMMAND
        mkdir -p $PIPE_DIR
        /usr/bin/env run_erl -daemon $PIPE_DIR/ $RUNNER_LOG_DIR \
            "exec $RUNNER_SCRIPT_DIR/$SCRIPT console" 2>&1
        ;;

    stop)
        UNAME_S=`uname -s`
        case $UNAME_S in
            Darwin)
                # Make sure we explicitly set this because iTerm.app doesn't for
                # some reason.
                COMMAND_MODE=unix2003
        esac
        # Wait for the node to completely stop...
        case $UNAME_S in
            Linux|Darwin|FreeBSD|DragonFly|NetBSD|OpenBSD)
                # PID COMMAND
                PID=`ps ax -o pid= -o command=|\
                    grep "$RUNNER_BASE_DIR/.*/[b]eam"|awk '{print $1}'`
                ;;
            SunOS)
                # PID COMMAND
                PID=`ps -ef -o pid= -o args=|\
                    grep "$RUNNER_BASE_DIR/.*/[b]eam"|awk '{print $1}'`
                ;;
        esac
        $NODETOOL stop
        while `kill -0 $PID 2>/dev/null`;
        do
            sleep 1
        done

        # Log the stop
        logger -t "$SCRIPT[$$]" "Stop"
        ;;

    restart)
        ## Restart the VM without exiting the process
        $NODETOOL restart
        ;;

    reboot)
        ## Restart the VM completely (uses heart to restart it)
        $NODETOOL reboot
        ;;

    ping)
        ## See if the VM is alive
        $NODETOOL ping
        ;;

    attach)
        # Make sure a node IS running
        RES=`$NODETOOL ping`
        if [ "$RES" != "pong" ]; then
            echo "Node is not running!"
            exit 1
        fi

        shift
        /usr/bin/env to_erl $PIPE_DIR
        ;;

    console)
        RES=`$NODETOOL ping`
        if [ "$RES" = "pong" ]; then
            echo "Node is already running - use '$SCRIPT attach' instead"
            exit 1
        fi
        # Setup beam-required vars
        ROOTDIR=$RUNNER_BASE_DIR
        BINDIR=$ERTS_PATH
        EMU=beam
        PROGNAME=`echo $0 | sed 's/.*\///'`
        CMD="$BINDIR/erlexec -boot $SHIRASU_BASE_DIR/releases/$APP_VSN/$SCRIPT \
            -embedded -config $RUNNER_ETC_DIR/app.config \
            -args_file $RUNNER_ETC_DIR/vm.args -- ${1+"$@"}"
        export EMU
        export ROOTDIR
        export BINDIR
        export PROGNAME

        # Dump environment info for logging purposes
        echo "Exec: $CMD"
        echo "Root: $ROOTDIR"

        # Log the startup
        logger -t "$SCRIPT[$$]" "Starting up"

        # Start the VM
        exec $CMD
        ;;

    *)
        echo "Usage: $SCRIPT {start|stop|restart|reboot|ping|console|attach}"
        exit 1
        ;;
esac

exit 0
